package cn.code.mycloud.module.system.service.aqi;

import cn.code.mycloud.framework.ip.core.Area;
import cn.code.mycloud.framework.ip.core.utils.AreaUtils;
import cn.code.mycloud.framework.security.core.LoginUser;
import cn.code.mycloud.framework.security.core.util.SecurityFrameworkUtils;
import cn.code.mycloud.module.system.controller.admin.screen.Constants;
import cn.code.mycloud.module.system.service.permission.PermissionService;
import cn.code.mycloud.module.system.util.aqi.AQIUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.code.mycloud.module.system.controller.admin.aqi.vo.*;
import cn.code.mycloud.module.system.dal.dataobject.aqi.AqiDO;
import cn.code.mycloud.framework.common.pojo.PageResult;
import cn.code.mycloud.framework.common.pojo.PageParam;
import cn.code.mycloud.framework.common.util.object.BeanUtils;

import cn.code.mycloud.module.system.dal.mysql.aqi.AqiMapper;

import static cn.code.mycloud.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.code.mycloud.module.system.enums.ErrorCodeConstants.*;

/**
 * AQI Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class AqiServiceImpl implements AqiService {

    @Resource
    private AqiMapper aqiMapper;

    @Resource
    private PermissionService permissionService;

    @Override
    public Long createAqi(AqiSaveReqVO createReqVO) {
        // 插入
        AqiDO aqi = BeanUtils.toBean(createReqVO, AqiDO.class);
        aqiMapper.insert(aqi);
        // 返回
        return aqi.getId();
    }

    @Override
    public void updateAqi(AqiSaveReqVO updateReqVO) {
        // 校验存在
        validateAqiExists(updateReqVO.getId());
        // 更新
        AqiDO updateObj = BeanUtils.toBean(updateReqVO, AqiDO.class);
        aqiMapper.updateById(updateObj);
    }

    @Override
    public void deleteAqi(Long id) {
        // 校验存在
        validateAqiExists(id);
        // 删除
        aqiMapper.deleteById(id);
    }

    private void validateAqiExists(Long id) {
        if (aqiMapper.selectById(id) == null) {
            throw exception(AQI_NOT_EXISTS);
        }
    }

    @Override
    public AqiDO getAqi(Long id) {
        return aqiMapper.selectById(id);
    }

    @Override
    public PageResult<AqiDO> getAqiPage(AqiPageReqVO pageReqVO) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        // 判断当前登录用户的角色，如果是管理员，则查询所有数据，如果是监督员，则查询该用户的数据，如果是网格员，则查询该网格的
        if(user !=null){
            Long userId = user.getId();
            if(permissionService.hasAnyRoles(userId,"NEPS")) {
                pageReqVO.setUserId(userId);
            }
            if(permissionService.hasAnyRoles(userId,"NEPG")) {
                pageReqVO.setGridUserId(userId);
            }
        }
        // FIXME 其他角色也需要控制
        return aqiMapper.selectPage(pageReqVO);
    }

    @Override
    public void assignGridUser(AqiAssignReqVO aqiAssignReqVO) {
        // 校验存在
        validateAqiExists(aqiAssignReqVO.getId());
        // 更新
        AqiDO updateObj = BeanUtils.toBean(aqiAssignReqVO, AqiDO.class);
        aqiMapper.updateById(updateObj);
    }

    @Override
    public List<AqiDO> selectAll() {
        return aqiMapper.selectList();
    }

    @Override
    public List<AqiDO> selectAllDone() {
        return aqiMapper.selectList(new LambdaQueryWrapper<AqiDO>().eq(AqiDO::getStatus, 2));
    }

    @Override
    public Map<String, Long> selectAllAqiWithProvince() {
        List<Map> aqiDOList =aqiMapper.selectAqiWithProvince();
        aqiDOList.removeIf(map -> (int)map.get("aqi_confirm") <= 50);

//        Map<String, Long> aqiDOMap = aqiDOList.stream().collect(
//                Collectors.groupingBy(map -> {
//                    String province = (String) map.get("province_name");
//                    return province;
//                },Collectors.counting())
//        );

        Area area = AreaUtils.getArea(Area.ID_CHINA);

        // 假设 provinces 是一个包含所有省份名称的集合
        Set<String> allProvinces = area.getChildren().stream().map(Area::getName).collect(Collectors.toSet());

        // 初始化结果Map
        Map<String, Long> aqiDOMap = new HashMap<>();

        // 现在将实际数据计入
        aqiDOList.forEach(map -> {
            String provinceName = (String) map.get("province_name");

            aqiDOMap.merge(provinceName, 1L, Long::sum); // 对于每个实际存在的省份，计数加1
        });


//        Map<String,Long> result = new HashMap<>();
//        aqiDOMap.forEach((k,v) -> {
//            String provinceAbbr = Constants.provinceFullNameToAbbr.getOrDefault(k, k);
////            System.out.println(k + ":" + v);
//            result.put(provinceAbbr, v);
//        });

        return aqiDOMap;
    }

    @Override
    public Map<String, Long> selectOneAqiWithProvince(String columnName) {
        List<Map> aqiDOList =aqiMapper.selectAqiWithProvince();
        aqiDOList.forEach(map -> {
            Map aqiByParam = null;
            if(columnName.equals("pm25_confirm")){
                aqiByParam = AQIUtils.getAQIByParam(null, null, null, null, Double.valueOf((String)map.get(columnName)), null, AQIUtils.DAQI);
            }else if (columnName.equals("so2_confirm")){
                aqiByParam = AQIUtils.getAQIByParam(Double.valueOf((String)map.get(columnName)), null, null, null, null, null, AQIUtils.DAQI);
            }else if (columnName.equals("co_confirm")){
                aqiByParam = AQIUtils.getAQIByParam(null, null, null, null, null, Double.valueOf((String)map.get(columnName)), AQIUtils.DAQI);
            }
            if(aqiByParam != null){
                map.put("aqi", aqiByParam.get("aqi"));

            }
        });

        aqiDOList.removeIf(map -> (int)map.get("aqi") <= 50);

//        Map<String, Long> aqiDOMap = aqiDOList.stream().collect(
//                Collectors.groupingBy(map -> {
//                    String province = (String) map.get("province_name");
//                    return province;
//                },Collectors.counting())
//        );

        Area area = AreaUtils.getArea(Area.ID_CHINA);

        // 假设 provinces 是一个包含所有省份名称的集合
        Set<String> allProvinces = area.getChildren().stream().map(Area::getName).collect(Collectors.toSet());

        // 初始化结果Map，对于所有省份，初始计数为0
        Map<String, Long> aqiDOMap = allProvinces.stream()
                .collect(Collectors.toMap(
                        Function.identity(), // 省份名称作为键
                        province -> 0L)); // 初始计数为0

        // 现在将实际数据计入
        aqiDOList.forEach(map -> {
            String provinceName = (String) map.get("province_name");

            aqiDOMap.merge(provinceName, 1L, Long::sum); // 对于每个实际存在的省份，计数加1
        });


        Map<String,Long> result = new HashMap<>();
        aqiDOMap.forEach((k,v) -> {
            String provinceAbbr = Constants.provinceFullNameToAbbr.getOrDefault(k, k);
//            System.out.println(k + ":" + v);
            result.put(provinceAbbr, v);
        });

        return result;
    }




}